/**
 * Copyright [2020] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.callcenter.gateway.filter;

import cn.hutool.core.date.StopWatch;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @project-name:callcenter
 * @package-name:com.hyts.callcenter.gateway.filter
 * @author:LiBo/Alex
 * @create-date:2021-12-12 1:26 下午
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
@Component
public class SystemCenterAuthFilter implements GlobalFilter, Ordered {


    @Autowired
    RestTemplate restTemplate;

    /**
     * 过滤器操作
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        StopWatch stopWatch  = new StopWatch();
        ServerHttpRequest request = exchange.getRequest();
        log.info("请求的操作处理自己——> url:{} -> method:{} -> body:{}",
                request.getPath().toString(),
                request.getMethod().name());
        String result = restTemplate.postForObject("http://callcenter-security/"+request.getPath().toString(),new HashMap<>(),String.class);
        log.info("结果执行：{}",result);
        stopWatch.start();
        HttpHeaders httpHeaders = exchange.getResponse().getHeaders();
        //返回数据格式
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        try {
            return exchange.getResponse().writeWith(Flux.just(result)
                    .map(bx -> {
                        try {
                            return exchange.getResponse().bufferFactory()
                                    .wrap(bx.getBytes("UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //调用请求之前统计开始
//        return chain.filter(exchange).then().then(Mono.fromRunnable(() -> {
//             //调用请求之后统计时间
//             stopWatch.stop();
//             log.info("计算所有的先关数据信息耗时:{}",stopWatch.getTotalTimeMillis());
//        }));
    }

    /**
     * 获取信息数据结构
     * @param serverHttpRequest
     * @return
     */
    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest){
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());

        });
        return bodyRef.get();
    }


    /**
     * 排序控制
     * @return
     */
    @Override
    public int getOrder() {
        return 10;
    }
}
